<?php

declare(strict_types=1);

namespace app\register\controller;

use thans\jwt\facade\JWTAuth;
use app\BaseController;
use app\model\User;

class Index extends BaseController
{
    /**
     * 处理用户登录逻辑
     * 
     * @return Array
     */
    public function index()
    {
        $params = $this->request->param();
        $DBuser = new User();
        $info  = $DBuser->where($params['type'], $params['username'])->select();
        if (!$info->isEmpty()) {
            // 如果查到该用户名存在，就返回用户名已存在
            return result(null, '该' . ($params['type'] == 'email' ? '邮箱' : '手机号') . '已注册', 401);
        }
        // 如果没有查询到注册的信息，那么就进行注册逻辑
        $registerInfo =  $DBuser->save(['username' => $params['username'], 'password' => $params['password'], $params['type'] => $params['username'], 'nickname' => $params['username']]);
        if ($registerInfo) {
            $i  = $DBuser->where('username', $params['username'])->field('avatar,email,id,mobile,nickname,username')->find();
            $token = JWTAuth::builder(['uid' => $i['id']]);
            return result(['token' => "bearer $token", 'username' => $i['username'], 'id' => $i['id'], 'avatar' => $i['avatar'], 'mobile' => $i['mobile'], 'nickname' => $i['nickname'], 'gender' => $i['gender'], 'occupation' => $i['occupation'], 'city' => $i['city'], 'birthday' => $i['birthday']], '注册成功');
        }
    }
}
